package com.yjy.test7_order;

import com.yjy.test6_tx.TransactionListenerImpl;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.concurrent.*;

/**
 * 顺序消息
 * 描述：在某些业务场景中，consumer在消费消息时，是需要按照生产者发送消息的顺序进行消费的。比如电商系统中的订单的消息，会有创建订单、支付订单、订单完成，这种消息的顺序不允许发生改变
 */
public class OrderProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("producer7");
        producer.setNamesrvAddr("192.168.145.128:9876");
        producer.setVipChannelEnabled(false);
        producer.start();

        // 模拟100个请求，但实际只有10个订单
        for (int i = 0; i < 100; i++) {
            String msgStr = "order -->" + i;
            int orderId = i % 100; // 模拟生成订单id
            Message message = new Message("topic7", "tagA", msgStr.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(message, (mqs, msq, arg) -> {
                Integer id = (Integer) arg;
                int index = id % mqs.size();
                return mqs.get(index);
            }, orderId);
            System.out.printf("i=%d, result:[%s]", i, sendResult);
        }
        producer.shutdown();
    }
}
